package com.ls.pattern.proxy.dynamicproxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class TransactionHandlerByCglib implements MethodInterceptor {

    @SuppressWarnings("unchecked")
    public <T> T getInstance(Class<T> target) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target);
        enhancer.setCallback(this);
        return (T) enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

        before();

        Object obj = null;
        try {
            obj = methodProxy.invokeSuper(o, objects);
        } catch (Exception e) {
            afterThrowing();
        }

        after();
        return obj;
    }

    private void before() {
        System.out.println("开启事务");
    }

    private void after() {
        System.out.println("提交事务");
    }

    private void afterThrowing() {
        System.out.println("回滚事务");
    }
}